package com.strat.searcher.lucene.searching;

import java.io.IOException;

import org.apache.commons.lang.Validate;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.strat.searcher.exceptions.IndexingException;

public class IndexSearcherWrapper {

    private IndexSearcher searcher;

    private static Logger logger = LoggerFactory.getLogger(Searcher.class);

    public IndexSearcherWrapper(Directory dir) {
        try {
            this.searcher = new IndexSearcher(dir);
        } catch (CorruptIndexException e) {
            logger.error("error", e);
            throw new IndexingException(e);
        } catch (IOException e) {
            logger.error("error", e);
            throw new IndexingException(e);
        }
    }

    public TopDocs search(Query query, int n) {
        Validate.notNull(searcher);
        try {
            return searcher.search(query, n);
        } catch (IOException e) {
            logger.error("error", e);
            throw new IndexingException(e);
        }
    }

    public void close() {
        Validate.notNull(searcher);
        try {
            searcher.close();
        } catch (IOException e) {
            logger.error("error", e);
            throw new IndexingException(e);
        }
    }

}
